package UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    DatagramSocket socket=null;
    //设置端口号
    public UdpEchoServer(int port) throws SocketException {
        socket=new DatagramSocket(port);
    }
    //启动服务器
   public void start() throws IOException {
       System.out.println("启动服务器");
       while (true){
           //1、读取请求解析
           DatagramPacket requestpacket=new DatagramPacket(new byte[4096],4096);
           socket.receive(requestpacket);
           //此时数据是以二进制的形式存放早数组中，将其以字符串形式显示
           String request=new String(requestpacket.getData(),0,requestpacket.getLength());
           //2.响应
           String response=process(request);
           //3.响应回到客户端
           DatagramPacket responsePacket=new DatagramPacket(response.getBytes(),response.getBytes().length,requestpacket.getSocketAddress());
           socket.send(responsePacket);
           //4.打印日志

           System.out.printf("[%s:%d] req=%s, resp=%s\n",requestpacket.getAddress().toString(),requestpacket.getPort(),request,response);
       }
   }

    private String process(String request) {
        return request;
    }
    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer=new UdpEchoServer(9090);
        udpEchoServer.start();

    }
}
